<?php
header('content-Type=text/html;charset=utf-8');
/*由于需求不确定，以下这些代码都是在不停的修改中，以后一定要重构这里的代码*/
class IndexAction extends Action {
  private $_dev = 1;
  private $_uid = 0;
  private $_channel_list = array(1=>"最新",2=>"热点",3=>"行业",4=>"专业",5=>"地区");
  private $_setting_list = array(1=>"行业",2=>"专业",3=>"地区");

  private $_navigation_list = array(
    name=>array(1=>"新闻",2=>"法规",3=>"资料"),
    table=>array(1=>array('phome_ecms_news','phome_ecms_news_data_1'),2=>'a_law',3=>'a_doc'),
    select=>array(
        1=>'id,title,username,FROM_UNIXTIME(lastdotime) as updatetime',
        2=>'id,ltitle as title,luser as username,ldate_pub as updatetime,lcontent as content',
        3=>'id,title,owner_name as username,from_unixtime(add_time) as updatetime,swf_file_name as content'
    ),
    orderby=>array(1=>'updatetime desc',2=>'ldate_pub desc',3=>'add_time desc'),
    key=>array(
        1=>array(left_table=>array(1=>'a_hy',2=>'a_zy',3=>'a_region'),top_table=>'phome_ecms_news',content_table=>'phome_ecms_news_data_1',join_id=>array(1=>"classid",2=>"idd",3=>"a_region")),
        2=>array(left_table=>array(1=>'a_hy',2=>'a_zy',3=>'a_region'),top_table=>'a_law',content_table=>'a_law',join_id=>array(1=>"hy_id",2=>"zy_id",3=>"a_region")),
        3=>array(left_table=>array(1=>'a_hy',2=>'a_zy',3=>'a_region'),top_table=>'a_doc',content_table=>'a_doc',join_id=>array(1=>"hy_id",2=>"zy_id",3=>"a_region"))
    )

  );
  /*  1,2,3代表新闻，法规，资料
     *  orderby 1-最新，2-热点
  */
  private $_lastAndHot = array(
    1=>array(
        sql=>"select id,title,username,FROM_UNIXTIME(lastdotime) as updatetime from phome_ecms_news where 1 and  ",
        name=>array("事故","企业动态","政府公告","媒体热点"),
        id=>'news_id',
        orderby => array(1=>" updatetime desc ",2=>" onclick desc ")
    ),
    2=>array(
        sql=>"select id,ltitle as title,luser as username,ldate_pub as updatetime from a_law where 1 and ",
        name=>array(1=>'法律',2=>'行政法规',3=>'司法解释',4=>'部门规章',5=>'地方性法规',6=>'地方政府规章',7=>'条例',8=>'国际条约',9=>'标准',10=>'其它'),
        id=>'lawtype_id',
        orderby => array(1=>" updatetime desc ",2=>" onclick desc ")
    ),
    3=>array(
        sql=>"select id,title,owner_name as username,from_unixtime(add_time) as updatetime from a_doc where 1 and isswf=1 and  ",
        name=>array(0=>'WORD文档',1=>'PPT文档',2=>'EXCEL文档',99=>'其他文档'),
        id=>'type',
        orderby => array(1=>" add_time desc ",2=>" download_num desc ")
    )
  );
  function _initialize() {
    $this->_dev = C("DEV_FLAG");
    if ($this->_dev == 1) {
      $this->_uid = 3;
    }else {
      if ($_COOKIE['tpxslmluserid'] > 0) {
        $this->_uid = $_COOKIE['tpxslmluserid'];
      } else redirect("http://www.ehs.cn/",1,'用户验证有错，请重新登陆~~~');
    }

  }

  public function checkSettingConfig() {
    $m = M('AMembersSettingHzr');
    $rt = $m->where("uid=".$this->_uid)->findAll();
    if ($rt && $rt != "") return 1;
    else return 0;
  }

  private function checkUID() {
    if ($_REQUEST["uid"] != $this->_uid) {
      $this->redirect('index/index', '', 1,'用户ID出错，请重新登陆，页面跳转中~');
    }
  }

  public function index() {
    $initChannel = $this->checkSettingConfig();
    $user = M("AMembersSettingHzr");
    $nid = ($_REQUEST['nid'])?$_REQUEST['nid']:1;
    $list = $user->where("uid = ".$this->_uid)->find();
    $info = array(1=>array(),2=>array(),3=>array(),4=>array(),5=>array());
    $obj = array(
      key=>array(1=>"hids",2=>"zids",3=>"rids"),
      table=>array(1=>"a_hy",2=>"a_zy",3=>"a_region"),
      select=>array(
        1=>array(1=>"news_classid as id,title,did",2=>"id,title,did",3=>"id,title,did"),
        2=>array(1=>"id,title,did",2=>"id,title,did",3=>"id,title,did"),
        3=>array(1=>"id,title,did",2=>"id,title,did",3=>"id,title,did")
      )
    );
    $lastAndHot = $this->_lastAndHot;
    for ($i = 1; $i < 3; $i++) {
      $vv = $lastAndHot[$nid];
      $temp = array();
      foreach($vv["name"] as $k => $v) {
        $temp[] = array(id=>$k,title=>$v);
      }
      $info[$i] = $temp;
    }

    /*行业，专业，地区*/
    foreach ($obj["key"] as $key => $value) {
      if ($list[$obj["key"][$key]] == "") continue;
      $select = $obj["select"][$nid][$key];
      $sql = "select ".$select." from ".$obj["table"][$key]." where id in (".$list[$obj["key"][$key]].")";
      $info[$key+2] = $user->query($sql);
    }
    $rt = $this->_getContentByNid($nid);
    $this->assign('issetting', $initChannel);
    $this->assign("uid",$this->_uid);
    $this->assign('nid',$nid);
    $this->assign('cid', $rt['content']['id']);
    $this->assign('ctitle',$rt['content']['title']);
    $this->assign("channel",$this->_channel_list);
    $this->assign('info',$info);
    $this->assign("newsList", $rt['list']);
    $this->assign('newsContent',$rt['content']);
    $favorite = $this->_initFavorite($this->_uid,$nid);
    $this->assign('favorite',$favorite);
    $this->assign("dev", $this->_dev);
    $this->assign("channelName",$this->_navigation_list["name"][$nid]);
    $this->display();
  }

  //可以考虑将虾下面两个函数合并，跟js里面的两个一起合并
  /*  params: $uid        用户的id
   *  params: $nid        1-新闻，2-法规，3-资料
   *  params: $join_id    1-最新，2-热点，3-行业，4-专业，5-地区
  */
  public function ajaxClickChannel() {
    $this->checkUID();
    $m = M('');
    $id = $_POST['id'];
    $nid = $_POST['nid'];
    $join_id = $_POST["join_id"];
    if ($join_id < 3) {
      $lastAndHot = $this->_lastAndHot;
      if ($id == 99) {
        $where = $lastAndHot[$nid]["id"].">2";
      }else {
        $where = $lastAndHot[$nid]["id"]."=".$id;
      }
      $sql = $lastAndHot[$nid]["sql"].$where." order by ".$lastAndHot[$nid]['orderby'][$join_id]." limit 5";
      $list = $m->query($sql);
      $this->ajaxReturn($list,"成功",1);
    } else {
      $list = $this->_navigation_list;
      $leftTable = $list["key"][$nid]["left_table"][$join_id-2];
      if ($join_id == 3 && $nid = 1) {
        $sql = "select t2.news_classid as id from $leftTable t1 left join $leftTable t2 on (t1.id = t2.did) where t1.news_classid = $id";
      }else $sql = "select id from $leftTable where did = $id";
      $rt = $m->query($sql);
      foreach ($rt as $i => $v) {
        $ids[] = $v["id"];
      }
      $ids = implode(',', $ids);
      $joinID = $list['key'][$nid]['join_id'][$join_id-2];
      $sql = "select ".$list["select"][$nid]." from ".$list['key'][$nid]["top_table"]." where ".$joinID." in (".$ids.") order by ".$list["orderby"][$nid]." limit 5";
      $list = $m->query($sql);
      $this->ajaxReturn($list,"成功",1);
    }
  }

  public function ajaxClickTitle() {
    $this->checkUID();
    $id = $_POST['id'];
    $nid = $_POST['nid'];
    $tempSql = array(
      1=>"select t1.id,t2.title,t1.newstext as content,FROM_UNIXTIME(t2.lastdotime) as updatetime  from phome_ecms_news_data_1 t1 left join phome_ecms_news  t2 on (t1.id=t2.id) where t1.id = $id",
      2=>"select id,ltitle as title,lcontent as content,ldate_pub as updatetime from a_law where id=$id",
      3=>"select id,title,swf_file_name as content,FROM_UNIXTIME(add_time) as updatetime from a_doc where id=$id"
    );
    $m = M('');
    //$sql = "select t1.id,t1.newstext as content,t2.title,FROM_UNIXTIME(t2.lastdotime) as updatetime  from phome_ecms_news_data_1 t1 left join phome_ecms_news  t2 on (t1.id=t2.id) where t1.id = $id";
    $sql = $tempSql[$nid];
    $newsContent = $m->query($sql);
    $newsContent = $newsContent[0];
    $newsContent['content'] = stripslashes($newsContent['content']);
    $this->ajaxReturn($newsContent,"成功",1);
  }

  private function _getContentByNid($id) {
    $m = M('');
    $rt = array();
    $obj = $this->_navigation_list;
    if($id == 1) {
      $sql = "select ".$obj['select'][$id]." from ".$obj["table"][$id][0]." order by ".$obj["orderby"][$id]." limit 5";
      $newsList = $m->query($sql);
      $newsID = $newsList[0]['id'];
      $sql = "select t1.id,t1.newstext as content,t2.title,FROM_UNIXTIME(t2.lastdotime) as updatetime  from ".$obj["table"][$id][1]." t1 left join phome_ecms_news  t2 on (t1.id=t2.id) where t1.id = $newsID";
      $newsContent = $m->query($sql);
      $newsContent = $newsContent[0];
      $newsContent['content'] = stripslashes($newsContent['content']);
    } else {
      $where = ($id == 3)?" where isswf = 1 ":"";
      $sql = "select ".$obj['select'][$id]." from ".$obj["table"][$id].$where." order by ".$obj["orderby"][$id]." limit 5";
      $newsList = $m->query($sql);
      $newsID = $newsList[0]['id'];
      $sql = "select ".$obj['select'][$id]." from ".$obj["table"][$id].$where." order by ".$obj["orderby"][$id]." limit 1";
      $newsContent = $m->query($sql);
    }
    $rt["list"] = $newsList;
    $rt["content"] = $newsContent;
    return $rt;
  }

  /*  params: $uid  用户id
   *  params: $nid  1-新闻，2-法规，3-资料
   *  return {id:1,name:name,level:level,list:{},downLine:{[id:2,name:name,level:level,downLine:{},list:{[]}]}}
  */
  private function _initFavorite($uid,$nid) {
    $rt = array();
    $fids = array();
    $m = M('AFavorite');
    $list = $m->where("type=$nid and uid=$uid")->findAll();
    foreach ($list as $k => $v) {
      $fids[] = $v['id'];
    }
    $fids = implode(',', $fids);
    $m = M('AFavoriteList');
    $flist = $m->where("type=$nid and fid in (".$fids.")")->findAll();
    $rt = $this->_formatFavorite(array(),$list,$flist,0,1);
    return $rt;
  }

  /*  利用递归的方法，构建一个数组对象
   *  return array(id=>id,name=>name,level=>level,list=>array(),downLine=>array(id,name,level,list,downLine))
   *  注意：模板中有list=>array()，即使list作为key的话可能在if判断中有错，因此目前修改成为_list
  */
  private function _formatFavorite($rt,$list,$flist,$did=0,$level=1) {
    foreach ($list as $k => $v) {
      if ($v['did'] == $did) {
        $rt[$k] = array(id=>$v['id'],title=>$v["title"],level=>$v['level'],"_list"=>array(),downLine=>array());
        foreach ($flist as $key => $value) {
          if ($v['id'] == $value['fid']) {
            $rt[$k]['_list'][] = array(id=>$value["id"],type=>$value['type'],tid=>$value['tid'],title=>$value['title'],fid=>$value['fid']);
          }
        }
        $level++;
        $rt[$k]['downLine'] = $this->_formatFavorite(array(),$list,$flist,$v["id"],$level);
        $level--;
      }
    }
    return $rt;
  }

  public function ajaxSaveFavoriteName() {
    $id = $_POST['id'];
    if (!$id || $id <= 0) {
      $this->ajaxReturn('', "id为空，保存出错~~", 2);
    };
    //不知道为什么以下的写法有问题
    //$table = array("a_favorite"=>"AFavorite","a_favorite_list"=>"AFavoriteList");
    //$m = M($table[$_POST['table']]);
    //$data['title'] = $_POST['title'];
    //$m->where("id=$id")->save($data);
    $sql = "update ".$_POST['table']." set title='".$_POST['title']."' where id=$id";
    $m = M('');
    $m->execute($sql);
    $favorite = $this->_initFavorite($this->_uid,$_POST["type"]);
    $this->ajaxReturn($favorite,"成功",1);
  }


  public function setting() {
    $this->checkUID();
    if ($_REQUEST["uid"] != $this->_uid) {
      $this->redirect('index/index', '', 1,'用户ID出错，请重新登陆，页面跳转中~');
    }
    $user = M('AMembersSettingHzr');
    $ul = $user->where('uid = '.$this->_uid)->find();
    $userHZR = array(1=>$ul["hids"]?$ul["hids"]:null,2=>$ul['zids']?$ul['zids']:null,3=>$ul['rids']?$ul['rids']:null);
    $obj = array(
      1=>array(table=>'a_hy',ids=>explode(',', $ul["hids"]),title=>'行业'),
      2=>array(table=>'a_zy',ids=>explode(',', $ul["zids"]),title=>"专业"),
      3=>array(table=>"a_region",ids=>explode(',', $ul["rids"]),title=>'地区')
    );
    $rt = array();
    $m = M();
    foreach ($obj as $index => $value) {
      //if ($index > 1) continue;
      $table = $value["table"];
      $list = $m->query("select id,title from $table where did = 0");
      $rt[$index-1]["check"] = 0;
      $rt[$index-1]["title"] = $value['title'];
      $p = 0;
      $ids = array();
      foreach ($list as $k => $v) {
        $ids[] = $v["id"];
        $v["check"] = 0;
        foreach ($value["ids"] as $i => $id) {
          if ($v["id"] == $id) {
            $p++;
            $v["check"] = 1;
          }
        }
        $rt[$index-1]["classify"][] =$v;
      }
      if ($p == count($list)) $rt[$index-1]["check"] = 1;
      $rt[$index-1]["ids"] = implode(',', $ids);
    }
    $this->assign("uid",$this->_uid);
    $this->assign("setting",$this->_setting_list);
    $this->assign('list',$rt);
    $this->assign('userHZR',json_encode($userHZR));
    //dump($rt);
    $this->display("setting-default");

  }

  /*   原始版本，可以选择到二级菜单   */
  /*
  public function setting1() {
    $this->checkUID();
    if ($_REQUEST["uid"] != $this->_uid) {
      $this->redirect('index/index', '', 1,'用户ID出错，请重新登陆，页面跳转中~');
    }
    $user = M('AMembersSettingHzr');
    $ul = $user->where('uid = '.$this->_uid)->find();
    $userHZR = array(1=>$ul["hids"]?$ul["hids"]:null,2=>$ul['zids']?$ul['zids']:null,3=>$ul['rids']?$ul['rids']:null);
    $obj = array(
            1=>array(table=>'a_hy',model=>'AHy',ids=>explode(',', $ul["hids"])),
            2=>array(table=>'a_zy',model=>'AZy',ids=>explode(',', $ul["zids"])),
            3=>array(table=>"a_region",model=>'ARegion',ids=>explode(',', $ul["rids"]))
    );
    $p = 0;
    $rt = array();
    foreach ($obj as $index => $value) {
      $m = M($value['model']);
      $table = $value["table"];
      $list = $m->query("select t1.id,t1.title,t1.did as did,ifnull(t2.title,'') as dtitle from $table t1 left join $table t2 on (t1.did = t2.id)");
      $list = $this->_formatList($list);
      $n = 0;
      $rt[$index-1]['check'] = 0;
      foreach ($list as $l => $val) {
        $list[$l]["check"] = 0;
        $list[$l]["ids"] = "";
        $ids = array();
        $p = 0;
        foreach ($val["downLine"] as $k => $v) {
          $lid = $v["id"];
          $ids[] = $lid;
          $list[$l]["downLine"][$k]["check"] = 0;
          foreach ($obj[$index]["ids"] as $u) {
            if ($lid == $u) {
              $list[$l]["downLine"][$k]["check"] = 1;
              $p++;
              $n++;
              break;
            }
          }
        }
        $list[$l]["ids"] = implode(',', $ids);
        if ($p == count($list[$l]["downLine"])) $list[$l]["check"] = 1;
      }
      $idList = $m->findAll();
      foreach ($idList as $i => $idL) {
        if ($idL['did'] > 0) $sids[] = $idL["id"];
      }
      if (count($sids) == $n) $rt[$index-1]['check'] = 1;
      $rt{$index-1}["ids"] = implode(',', $sids);
      $rt[$index-1]["list"] = $list;
    }
    $this->assign("uid",$this->_uid);
    $this->assign("setting",$this->_setting_list);
    $this->assign('list',$rt);
    $this->assign('userHZR',json_encode($userHZR));
    //dump($rt);
    $this->display();
  }
  */

  /*
  private function _formatList($list) {
    $rt = array();
    for($i = 0,$len = count($list); $i < $len; $i++) {
      $l = $list[$i];
      if ($l["did"] == 0) $rt[] = array(id=>$l["id"],title=>$l["title"],downLine=>array());
    }
    for ($i = 0, $len = count($rt); $i < $len; $i++) {
      $r = $rt[$i];
      for ($j = 0, $lenght = count($list); $j < $lenght; $j++) {
        $l = $list[$j];
        if ($r["id"] == $l["did"]) $rt[$i]["downLine"][] = array(id=>$l["id"],title=>$l["title"]);
      }
    }
    return $rt;
  } */

  public function settingSave() {
    //dump($_POST);
    $m = M('AMembersSettingHzr');
    $uid = $_POST['uid'];
    $hids = $_POST['hids'];
    $zids = $_POST['zids'];
    $rids = $_POST['rids'];
    $sql = "insert into a_members_setting_hzr (uid,hids,zids,rids) values ($uid,'$hids','$zids','$rids') on duplicate key update
           hids='$hids', zids='$zids', rids='$rids'";
    $rt = $m->query($sql);
    if (is_array($rt)) {
      $this->redirect('index/index', '', 1,'配置成功，页面跳转中~');
    }else $this->redirect('index/index', '', 1,'配置出错，页面跳转中~');
  }

  public function ajaxSaveNewFavFile() {
    $m = M();
    $sql = "insert into a_favorite (`type`,`title`,did,level,uid) values (".$_POST['type'].",'".$_POST['title']."',".$_POST['did'].",".$_POST['level'].",".$_POST['uid'].")";
    $m->execute($sql);
    $favorite = $this->_initFavorite($this->_uid,$_POST['type']);
    $this->ajaxReturn($favorite,"成功",1);
  }

  public function ajaxSaveFavContent() {
    $m = M();
    $sql = "insert into a_favorite_list (`type`,`tid`,title,fid) values (".$_POST['type'].",".$_POST['tid'].",'".$_POST['title']."',".$_POST['fid'].")";
    $m->execute($sql);
    $favorite = $this->_initFavorite($this->_uid,$_POST['type']);
    $this->ajaxReturn($favorite,"成功",1);
  }

  public function ajaxDeleteFavList() {
    $id = $_POST['id'];
    $type = $_POST["nid"];//1-新闻，2-法规，3-资料
    $status = $_POST['type'];//1-删除文件夹和其下的所有子文件夹和文章，2-删除单一文章
    $m = M();
    if ($status == 1) {
      $sql = "select id,did,level from a_favorite where uid=".$this->_uid." and type=$type";
      $list = $m->query($sql);
      $ids = array($id);
      $ids = $this->_getIDSFavFile($ids,$list,$id);
      $ids = implode(',', $ids);
      $sql = "delete from a_favorite where id in ($ids)";
      $m->execute($sql);
      $sql = "delete from a_favorite_list where fid in ($ids)";
      $m->execute($sql);
    }else if ($status == 2) {
      $sql = "delete from a_favorite_list where id=$id";
      $m->query($sql);
    }
    $favorite = $this->_initFavorite($this->_uid,$type);
    $this->ajaxReturn($favorite,"成功",1);
  }

  private function _getIDSFavFile($ids,$list,$did) {
    foreach ($list as $k => $v) {
      if ($did == $v["did"]) {
        $ids[] = $v["id"];
        $ids = $this->_getIDSFavFile($ids,$list,$v['id']);
      }
    }
    return $ids;
  }

  //在左边列收藏夹，点击右键选择新建文件夹的功能
  public function newFavFile() {
    $m = M();
    $did = $_POST['id'];
    $sql = "insert into a_favorite (`type`,`title`,did,level,uid) values (".$_POST['type'].",'".$_POST['title']."',".$did.",".$_POST['level'].",".$_POST['uid'].")";
    $m->execute($sql);
    $favorite = $this->_initFavorite($this->_uid,$_POST['type']);
    $this->ajaxReturn($favorite,"成功",1);
  }
}
?>